package xmsj.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;




public class JDBCfind {
 
	 public static <T> T find(Class<T> clazz,String sql,Object ... ages){
		 Connection conn=null;
		 PreparedStatement prepareStatement=null;
		 ResultSet rs =null;
		 try {
			conn=JDBCUtils.getConnection();
			prepareStatement=conn.prepareStatement(sql);
			if(ages!=null){
				for(int i=0;i<ages.length;i++){
					prepareStatement.setObject(i+1, ages[i]);
				}
			}
			
			 rs = prepareStatement.executeQuery();
			 ResultSetMetaData rsmd = rs.getMetaData();
			 Map<String, Object> map=new HashMap<String, Object>();
			 while(rs.next()){
				 for(int j=0;j<rsmd.getColumnCount();j++){
					 String columnLabel =rsmd.getColumnLabel(j+1);
					 Object columnvalues=rs.getObject(columnLabel);
					 map.put(columnLabel, columnvalues);
				 }
			 }
			      Object object = clazz.newInstance();
				for(Map.Entry<String, Object> entry: map.entrySet()){
					String fieldName = entry.getKey();
					Object fieldValue = entry.getValue();
					ReflectionUtils.setFieldValue(object, fieldName, fieldValue);
				}
				
				System.out.println(object); 
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			JDBCUtils.close(rs, prepareStatement, conn);
		}
		 return null;
	 }
	 
	 public static void update(String sql,Object ... ages){
		Connection conn=null;
		PreparedStatement prepareStatement =null;
		try {
			conn=JDBCUtils.getConnection();
			prepareStatement=conn.prepareStatement(sql);
			if(ages!=null){
				for(int i=0;i<ages.length;i++){
					prepareStatement.setObject(i+1, ages[i]);
				}
			}
			prepareStatement.executeUpdate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			JDBCUtils.close(null, prepareStatement, conn);
		}
		
	 }

	
}
